import { defineStore } from 'pinia'
import {
  addToShoppingCartAPI,
  getCartListAPI,
  deleteCommodityAPI,
  updateCartGoodsAPI,
  updateAllCheckedAPI
} from '@/api'
export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      cartList: [] // 购物车数据
    }
  },
  getters: {
    // 计算总价格
    allPrice() {
      return this.cartList.reduce((prev, item) => prev + item.price * item.count, 0)
    },
    // 计算总数量
    allCount() {
      return this.cartList.reduce((prev, item) => prev + item.count, 0)
    },
    // 计算已选择几件商品
    selectedGoods() {
      return this.cartList.filter(item => item.selected).reduce((prev, item) => prev + item.count, 0)
    },
    // 商品合计
    allCheckedPrice() {
      return this.cartList.filter(item => item.selected).reduce((prev, item) => prev + item.price * item.count, 0)
    },
    // 计算是否全选
    isAllChecked() {
      return this.cartList.every(item=>item.selected)
    },
  },
  actions: {
    // 添加商品到购物车
    async addCartActions(data) {
      await addToShoppingCartAPI(data) // 增加
      const { result } = await getCartListAPI() // 获取新数据
      this.cartList = result
    },
    // 删除商品
    async deleteCommodityActions(data) {
      await deleteCommodityAPI(data) // 删除
      const { result } = await getCartListAPI() // 获取新数据
      this.cartList = result
    },
    // 更新单选按钮
    async updateCartGoodsActions(data) {
      await updateCartGoodsAPI(data)
      const { result } = await getCartListAPI() // 获取新数据
      this.cartList = result
    },
    // 更新全选
    async updateAllCheckedActions(selected) {
      await updateAllCheckedAPI({
        ids: this.cartList.map(item => item.skuId),
        selected
      })
      const { result } = await getCartListAPI() // 获取新数据
      this.cartList = result
    }
  },
  // 开启数据缓存
  persist: { enabled: true }
})
